package com.jqk.shoporder.controller;

import com.alibaba.fastjson.JSON;
import com.jqk.shoporder.bean.Order;
import com.jqk.shoporder.bean.Product;
import com.jqk.shoporder.feign.ProductService;
import com.jqk.shoporder.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:jiangqikun
 * @Date:2022/3/3 17:16
 **/
@RestController
@Slf4j
public class SeataController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @RequestMapping("/order/seata/{pid}")
    @GlobalTransactional(rollbackFor = Exception.class)
    public Order order(@PathVariable("pid") Integer pid){
        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", pid);
        Product product = productService.findByPid(pid);
        log.info("查询到{}号商品的信息,内容是:{}", pid, JSON.toJSONString(product));
        //1： 下单(创建订单)
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setUserName("下单用户");
        orderService.save(order);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        //2： 扣库存
        productService.reduceProduct(pid,1);
        log.info("库存扣减成功", JSON.toJSONString(order));
        return order;
    }

}
